﻿using System;
using System.Data;
using System.Data.Objects;
using System.Data.SqlClient;
using System.Linq;
using Complaint.Models.Dtos;

namespace Complaint.Repositories
{
    public abstract class BaseRepository<T> where T : class, new()
    {
        private ComplaintEntities _objCtx;
        protected internal ComplaintEntities ObjectContext
        {
            get
            {
                if (_objCtx != null)
                    return _objCtx;

                if (ObjectContextScope<ComplaintEntities>.CurrentObjectContext != null)
                    return ObjectContextScope<ComplaintEntities>.CurrentObjectContext;

                new ObjectContextScope<ComplaintEntities>();
                return ObjectContextScope<ComplaintEntities>.CurrentObjectContext;
            }
        }

        protected BaseRepository()
        {
        }

        protected BaseRepository(ComplaintEntities context)
        {
            _objCtx = context;
        }

        public void Update(T dto)
        {
            try
            {
                ObjectContext.SaveChanges();
            }
            catch (OptimisticConcurrencyException)
            {
                System.Diagnostics.Debug.WriteLine("OptimisticConcurrencyException occurred, "
                    + "attempting to resolve ...");
                ObjectContext.Refresh(RefreshMode.StoreWins, dto);
                ObjectContext.SaveChanges();
                System.Diagnostics.Debug.WriteLine("Concurrency confliction resolved.");
            }
            catch (SqlException se)
            {
                throw new ApplicationException("An exception occurred while saving your changes", se);
            }
        }

        public void Delete(T dto)
        {
            ObjectContext.DeleteObject(dto);
            Update(dto);
        }

        protected virtual IQueryable<T> LoadResult(IQueryable<T> result, int loadOption)
        {
            throw new NotImplementedException();
        }
    }
}
